// 将数字进行千分化，保留2位小数，金额为空返回0.00
export const formatAmount = (num) => {
  if (typeof num === 'undefined' || num === null || num.toString().trim() === '') {
    return 0.00;
  }
  num = num * 1;
  return num.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
};

// 格式化为中文金额（金额、小数位数）（超过兆级出错）
export function formatCurrency(money, decimalCount = 2) {
  let cnMoney = '零元整';
  let strOutput = '';
  let strUnit = '仟佰拾兆仟佰拾亿仟佰拾万仟佰拾元角分毫厘'; // length = 20
  strUnit = strUnit.slice(0, 16 + decimalCount); // 依据小数位数控制单位范围，最长4位
  money += new Array(decimalCount).fill(0).join('');
  let intPos = money.indexOf('.'); // 获取小数点的index
  if (intPos >= 0) {
    let newIdx = intPos + 1;
    money = money.slice(0, intPos) + money.slice(newIdx, newIdx + Math.min(decimalCount, 4));
  }
  strUnit = strUnit.slice(strUnit.length - money.length);
  for (let i = 0; i < money.length; i++) {
    let idx = Number(money.slice(i, i + 1));
    strOutput += '零壹贰叁肆伍陆柒捌玖'.slice(idx, idx + 1) + strUnit.slice(i, i + 1);
  }
  cnMoney = strOutput
    .replace(/零角零分零毫零厘$/, '整')
    .replace(/零分零毫零厘$/, '')
    .replace(/零毫零厘$/, '')
    .replace(/零厘$/, '')
    .replace(/零[仟佰拾]/g, '零')
    .replace(/零{2,}/g, '零')
    .replace(/零([兆|亿|万])/g, '$1')
    .replace(/零+元/, '元')
    .replace(/亿零{0,3}万/, '亿')
    .replace(/兆零{0,3}亿/, '兆')
    .replace(/^元/, '零元');
  return cnMoney;
}

// 四分数字
export function formatAccount(account) {
  let str = ((account || '') + '').replace(/^\s|\s$/g, '');
  let temp = '';
  for (let i = 0; i < str.length; i++) {
    temp = temp + str.substring(i, i + 1);
    if (i !== 0 && (i + 1) % 4 === 0 && i !== str.length - 1) {
      temp = temp + ' ';
    }
  }
  return temp;
}

// 表单序列化
export const serialize = data => {
  let list = [];
  Object.keys(data).forEach(key => {
    list.push(`${key}=${data[key]}`);
  });
  return list.join('&');
};

// 获取数据类型
export const getDataType = obj => {
  let toString = Object.prototype.toString;
  let dataMap = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  };
  if (obj instanceof Element) {
    return 'element';
  }
  return dataMap[toString.call(obj)];
};

// 防抖
export function debounce(fn, wait = 500, immediate = false) {
  let timer = null;
  let flag = true;
  return function () {
    let that = this;
    let args = [...arguments];
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    if (immediate) {
      if (flag) {
        fn.apply(that, args);
        flag = false;
      }
      timer = setTimeout(() => {
        flag = true;
      }, wait);
    } else {
      timer = setTimeout(() => {
        fn.apply(that, args);
      }, wait);
    }
  }
}

// 节流
export function throttle(fn, wait = 500, immediate = false) {
  let timer = null;
  let flag = true;
  if (immediate) {
    return function() {
      let that = this;
      let args = [...arguments];
      if (flag) {
        fn.apply(that, args);
        flag = false;
        timer = setTimeout(() => {
          flag = true;
        }, wait);
      }
    }
  }
  return function () {
    let that = this;
    let args = [...arguments];
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(that, args);
        timer = null;
      }, wait);
    }
  }
}
